###--------------------------------------------------------------------### # # R Codes for the practicals of "Fundamentals in Ecology" # # Bachelor 2 SIE - Sciences et Ingenierie de l'Environnement # Ecole polytechnique federale de Lausanne (EPFL) # # by Christoph Bachofen, Eugenie Mas, Hannes Peter, Jade Brandani, Jonas Paccolat # Acknowledgements to Lluis Gomez # ###--------------------------------------------------------------------### ###--------------------------------------------------------------------### ### 1. How does an R Studio session looks like? -------------------------- ###--------------------------------------------------------------------### ###---------------------------### # If you're not familiar with R and the RStudio environment, you should # first watch the video that explains the basic functionalities.You can # download it on the moodle site of the lecture. ###---------------------------### ########################################################################## ###--------------------------------------------------------------------### ### 2. Calculations ------------------------------------------------------ ###--------------------------------------------------------------------### ###---------------------------### # First, we are looking at the basic functionalities of R, and for this it's # easies to just do some simple calculations. Run the codes below, but # also change them, try to combine them to make more complex calculations, etc. ###---------------------------### # An addition 5 + 5 # A subtraction 5 - 5 # A multiplication 3 * 5 # A division (5 + 5) / 2 # An exponential 2 ^ 5 # Built-in Constants 2 * pi ^ 2 ########################################################################## ###--------------------------------------------------------------------### ### 3. Variables --------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Now, we are going to assign values to variables, which is done with the arrow # this: <- # you can also use the equal sign # this: = # but it's less common, and I encourage you to use the arrow for keeping your code tidy. ###---------------------------### # Assigning a number to a variable my_var <- 4 # Printing out the value of the variable my_var my_var # Calculations between assigned variables my_apples <- 5 my_oranges <- 4 my_fruits <- my_apples + my_oranges my_fruits # Overwrite a variable with a new number my_oranges <- 6 # Show all the objects you have created so far: (you can also check the environment window) ls() # In case you want to remove the variable: rm(my_fruits) # To remove all objects created you can click on the small brush in Environment window ########################################################################## ###--------------------------------------------------------------------### ### 4. Logicals ---------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Logical objects # A logical object contains only two types of values: TRUE or FALSE. You can # use them to test whether something is smaller or bigger, equal or different, etc. # For comparing values you use the following signs: # smaller: < # smaller or equal: <= # equal: == # not equal: != # larger or equal: >= # larger: > # and: & # inclusive or: | ###---------------------------### a <- 5 b <- 4 c <- 4 # Examples of logical tests a == b # is a equal to b? b == c # is b equal to c? a > b # is a larger than b? a != c # is a not equal (different from) c? a > b & c < a # is a larger than b and c smaller than a? a == b & c != a # is a equal to b and c not equal to a? a == b | c == b # is a equal to b or c equal to b? ########################################################################## ###--------------------------------------------------------------------### ### 5. Object classes ---------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # You can have objects of different types (classes) in your data. For instance, # names of places, number of trees, names of categories, etc. # In order to not make a mess, you should always know what class your object is, # because you cannot freely combine them. Examples are given below. ###---------------------------### # Error due to a mismatch in data types? 5 + "six" # this not work, because one of them is a number, the other a word. Both of them need to be a number 5 + 6 # now it works, because 6 is now a number, not a word. # We use the function "class" to check the class of our object. class(5) class("six") class(TRUE) # class() is a function that needs one input that is provided in the parantheses # 5 is a number # six is a character # TRUE is a logical statement ########################################################################## ###--------------------------------------------------------------------### ### 6. Functions --------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Next, we move to functions that we want to apply to our objects. Generally, # a function is written as a word that is followed by parantheses, like the examples # below. A function typically needs one or more inputs, and gives one or more outputs. # There are also functions that don't need input, but provide output, see one example below. # So, a function performs a task with the object or objects you give it. ###---------------------------### # See some examples: class(5) print("Hello") c(1, 2, 3, 4) # probably the most important function: it combines multiple objects into one. You need it to put it in as an argument in another function, see below. sum(c(4, 6)) # here, for instance, you combine 4 and 6 and hand it over to the function sum(). Exceptionally, sum(4, 6) also works, but better get used to combine your input with the c() mean(c(4, 6)) # same as before. But now, mean(4, 6) actually returns a wrong response, because it needs a combined vector as input, with the c(). Sys.time() # no input needed sqrt(9) sqrt(c(9, 16, 25, 36)) # you can also have multiple inputs, if you combine them with c(). This works with most functions. exp(1) log(2.718282) sin(pi / 2) cos(pi) round(5.23456789, 2) ceiling(5.23456789) floor(5.23456789) length(c(5, 4, 3, 2, 1, 0)) nchar("hello world") # find out what a function does: ?sum ?nchar ?length # Functions come in packages install.packages("car") library("car") # even if a package is installed on your computer, you have to activate the package with "library" every time you start R to be able to use the functions # Functions can be defined by ourselves my.se.function <- function(x) {sd(x)/sqrt(length(x))} # this is an example of a function that calculates the standard error based on the standard deviation, and the number of measurements my.se.function(c(1,2,3,4,5)) ########################################################################## ###--------------------------------------------------------------------### ### 7. Vectors ----------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # As shown before, you can combine several objects into one with the function c(). # When you do this, you get a vector of these object. You can then use this vector # in function, do calculations with it, etc. # When you do something with a vector, for instance a calculation, R generally # does it to each element of the vector. See below how that works. ###---------------------------### # A vector is a single object consisting of a collection of elements ###--------------------------------------### my_first_vector <- c(22, 6, 0.12, 32, 1011, 7.12, 25) my_first_vector ###--------------------------------------### # A vector can contain different types of values: ###--------------------------------------### # Numeric vectors my_first_numeric_vector <- c(22, 6, 0.12, 32, 1011, 7.12, 25) my_first_numeric_vector # Character vectors my_char_vector <- c("house", "apple", "42") my_char_vector # Logical vectors # A logical vector contains only two types of values: TRUE or FALSE my_first_logical_vector <- c(T, T, T, F, F, T, F) ###--------------------------------------### # We can ask R to tell us what class of vector do we have: ###--------------------------------------### class(my_first_logical_vector) ###--------------------------------------### # Create your own vector: ###--------------------------------------### seq(0, 10, 2) rep(4, 5) rep(c(1,2,3), 3) rep(c(1,2,3), each=3) rnorm(10, 2, 10) runif(10, 0, 1) ###--------------------------------------### # Now use logicals on vectors ###--------------------------------------### vec1 <- seq(0, 10, 2) vec2 <- rep(4, 6) ###--------------------------------------### # Element-wise comparison ###--------------------------------------### vec1 == vec2 3 < vec1 # it tests for each element of the vector, whether it smaller than 3 or not and returns a vector of TRUE and FALSE ###--------------------------------------### # "is-in" comparison ###--------------------------------------### 3 %in% vec2 # you can think of this as: "is there a 3 in the vector?" 4 %in% vec2 ###--------------------------------------### # Do math with vectors: ###--------------------------------------### vec1 * 2 vec1 ^ 2 ### element-wise addition vec1 + vec2 ### element wise addition and cycle through the second (shorter) vector vec3 <- c(1,2,3) vec1 + vec3 ### does not work, because vec4 is not a multiple (or fraction) of vec 1 ### so R does not know how what you want to do here. vec4 <- c(1,2,3,4) vec1 + vec4 ###--------------------------------------### # We can also give names to the elements of the vector: ###--------------------------------------### names(my_first_numeric_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") my_first_numeric_vector ###--------------------------------------### # We can also perfrom operation between vectors: ###--------------------------------------### A_vector <- c(1, 2, 3) B_vector <- c(4, 5, 6) total_vector <- A_vector + B_vector total_vector total_vector <- sum(A_vector, B_vector) total_vector ###--------------------------------------### # And we can combine vectors: ###--------------------------------------### C_vector <- c(A_vector, B_vector) ###--------------------------------------### ########################################################################## ###--------------------------------------------------------------------### ### 8. Subsetting -------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Subsetting data (e.g. vectors or dataframes) is a super important functionality in R to remember! # you are going to need it a lot, because you will select and structure your data # before analysing it. # To subset data we can very easily add brackets [ ] after an object (vector, dataframe, etc.) and # tell in the bracket, which element of the object we want to select. ###---------------------------### # in case you haven't, create the vector my_first_numeric_vector <- c(22, 6, 0.12, 32, 1011, 7.12, 25) names(my_first_numeric_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") # Select specific elements of a vector: ###--------------------------------------### my_first_numeric_vector[2] # for element number 2 in the vector my_first_numeric_vector[-2] # all elements, except the second one # Select combination of elements of a vector: my_first_numeric_vector[c(1, 5)] # the first and fifth element my_first_numeric_vector[1:3] # element one through three my_first_numeric_vector[-c(1:3)] # all elements, except one through three my_first_numeric_vector["Monday"] # if you have a name for the element, you can also use this name to select the element. my_first_numeric_vector[c("Monday","Tuesday")] ###--------------------------------------### ########################################################################## ###--------------------------------------------------------------------### ### 9. Dataframes -------------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Dataframes are the most common way in which you will have your data. # In this format, your data are easy to look at, subset, transform, plot # and do statistical analyses with. # You can think of a dataframe as a combination of multiple vectors. Basically, # it's how you usually have the data in Excel. # R comes with some example dataframes that we can use to discover how to handle # them. ###---------------------------### # How to create a dataframe ###--------------------------------------### # You can create a dataframe from multiple vectors, for instance like this df <- data.frame(A_vector, B_vector) # And you can also include new information like this df <- data.frame(A_vector, B_vector, fruit = c("apple", "pear", "orange")) df ###--------------------------------------### # Basic exploraton of the structure of a data frame: ###--------------------------------------### iris # first have a full look at the iris dataframe. It contains measurements of the flowers of different Iris species head(iris) # because it's too large for a normal screen, you can also only look at the beginning tail(iris) # or the end of the dataframe str(iris) # this gives you an overview of what's the structure of the dataframe: the columns, what class the data is, an overview of what it contains dim(iris) # how big your dataframe is ###--------------------------------------### # Numerical summary of data: ###--------------------------------------### summary(iris) ###--------------------------------------### # Getting column and rownames ###--------------------------------------### colnames(iris) rownames(iris) ###--------------------------------------### # Accessing columns and rows in a data frame ###--------------------------------------### # You can get the values of a specific column or row by using the same brackets as with the vector. # Only, this time you need to provide two values: the row number and the column number that you want to # have shown iris[2, 3] # [row, column] this provides the value that you find in row number 2 and column number 3 iris[ , 3] # if you leave the row argument empty, you tell R to give you all the rows (but just column 3) iris[2, ] # vice-versa, if you leave the column argument empty, you tell R to give you all the columns (but just row 2) # Using column name iris[, "Petal.Length"] #[row, column] instead of the column number, you can also use the column name # Using dollar notation = $ iris$Petal.Length # This is a special feature of dataframes: you can use the dollar sign to access columns iris$Petal.Length * 2 # you can manipulate the columns as the vectors before, e.g. do some math with it iris$Petal.Length < 2 # or some logical tests ###--------------------------------------### # Renaming and rerranging columns of a data frame ###--------------------------------------### iris2 <- iris # first, create a second iris dataframe, so that you don't overwrite the original one colnames(iris2) <- c("a", "b","c","d", "e") # you can change the names of the columns if you want head(iris2) ###--------------------------------------### # Add or delete a new column as a combination of two others ###--------------------------------------### iris$new_column <- iris$Petal.Length * iris$Petal.Length iris$new_column <- NULL ###--------------------------------------### # SUBSETTING data frames ###--------------------------------------### # there are different ways to subset a dataframe, either with "subset" or with the brackets [ ] subset(iris, iris$Species == "setosa") subset(iris, iris$Sepal.Length <= 5) iris[iris$Species == "setosa", ] # here you use a combination of a logical test (iris$Species == "setosa") with the fact that you can access rows and columns with the brackets iris[iris$Sepal.Length <= 5, ] ###--------------------------------------### # Aggregating data frames ###--------------------------------------### # aggregation is used do group-wise calculations, for instance means per species aggregate(Petal.Length ~ Species, data=iris, FUN=mean) aggregate(Petal.Length ~ Species, data=iris, FUN=sd) aggregate(Petal.Length ~ Species, data=iris, FUN=max) ###--------------------------------------### # MERGING or combining different data frames ###--------------------------------------### # Sometimes we have two dataframes with different measurements that we want to combine into one dataframe. # For instance, we want to make sure that they are combined species by species, and not mixed up. # Let's first create a new data frame that we then merge with iris iris2 <- data.frame(rnorm(150, 15, 5)) # create random fake data colnames(iris2) <- c("random_data") iris2 # now let's add information about species iris2$Species<-iris$Species # Merge Iris and Iris 2 by Species new_merge <- merge(iris, iris2, by="Species") ###--------------------------------------### # SORTING variables in a data frame ###--------------------------------------### # Sorting iris by Petal.Length (ascending) - order function iris$Petal.Length order(iris$Petal.Length) # the function order() shows you the order number, it doesn't actually sort the data ascending_petal <- iris[order(iris$Petal.Length), ] # you can use the order information to sort the rows with the brackets ascending_petal ###--------------------------------------### ### Data management with dplyr ### There is a package called dplyr, which contains a lot of functions that are helpful with ### sorting and filtering your data. I heavily recommend you learn it at some point. ########################################################################## ###--------------------------------------------------------------------### ### 10. Read in data ----------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # Last but not least: you need to know how to import data in R. Usually, you will have saved # the data in an excel file, that you will need to export as CSV ("save as"). This is # the best format to import it in R. ###---------------------------### # First, you will have to tell R where to get the file. You do this by setting the working directory # to the path where you find the file in your computer. # Careful: you might have some spaces in the names of your directories, e.g. "My R files". The spaces # must be inactivated with the backslash escape before each space "\", e.g. "My\ R\ files". # First see to which path the working directory is set getwd() ### this is again a function that does not need an argument # Set the working directory to the place you find the file. setwd("...your working directory...") # Another option: go in "Files" in the plots window and go in the folder where you have your excel files, then go in "More" => "Set as working directory", it allows you to avoid to have to write manually the path of your file # Loading data set (example) my.new.data <- read.delim('biomass-data.csv', sep=',', header=T) # alternatively: # read.table() # read.csv() ########################################################################## ###--------------------------------------------------------------------### ### 11. Write out data --------------------------------------------------- ###--------------------------------------------------------------------### ###---------------------------### # The same that was true for importing is also the case for exporting: you want # to know where your file ends up being saved. So, you should make sure your # working direcory is set to the location you want to have the file saved. ###---------------------------### # Setting working directory setwd("...your working directory...") # To a tab or comma separated text file write.table(my_first_numeric_vector, "biomass-data-2.csv", sep=",") write.table(my_first_numeric_vector, "biomass-data-2.csv", sep="\t") # other writing options: # write.csv() # write.xlsx() # if you want to write data that you're only going to use in R, then # you can use save(). And to read in you use load(). save(my_first_numeric_vector, file = "my_first_numeric_vector.Rdata") load(file = "my_first_numeric_vector.Rdata") ##########################################################################